/**
 * Created by yangzhao.lyz on 17/4/17.
 */


import { transform, BabelFileResult } from 'babel-core';
import CommonJsLoader from './SourceLoader';
import detective = require('detective');
import path = require('path');
import File from '../file/File';
import BaseSourceFile from '../file/BaseSourceFile';
import SourceLoader from './SourceLoader';

export default class JsLoader extends SourceLoader {
    async load(file: File) {
        let result: BabelFileResult = {
            code: file.contents
        };
        if (file.type === FileType.source || file.type === FileType.module && file.cx.options.transformLibrary) {
            result = transform(result.code || '', file.cx.options.babel);
        }
        let found = detective.find(result.code);
        for (let dependency of found.strings) {
            file.dependencies[dependency] = File.obtain(file.cx, dependency, path.dirname(file.src || ''));
        }
        file.contents = result.code || '';
        await super.load(file);
    }
}
